package com.lbs.jiepiaisi.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.activity.AccountChaseCarAcitivty;
import com.lbs.jiepiaisi.activity.AccountUserInfoActivity;
import com.lbs.jiepiaisi.activity.AlarmListActivity;
import com.lbs.jiepiaisi.activity.HistoryTraceActivity;
import com.lbs.jiepiaisi.activity.TracingActivity;
import com.lbs.jiepiaisi.adapter.DeptListAdapter;
import com.lbs.jiepiaisi.adapter.EquipListAdapter;
import com.lbs.jiepiaisi.base.BaseFragment;
import com.lbs.jiepiaisi.base.ErrorException;
import com.lbs.jiepiaisi.base.ProgressObserver;
import com.lbs.jiepiaisi.bean.DeptsEntity;
import com.lbs.jiepiaisi.bean.EquipBean;
import com.lbs.jiepiaisi.bean.TrackEntity;
import com.lbs.jiepiaisi.config.Api;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.utils.Constant1;
import com.lbs.jiepiaisi.utils.RxSchedulers;
import com.lbs.jiepiaisi.utils.SpUtil;
import com.lbs.jiepiaisi.utils.ToastUtil;
import com.lbs.jiepiaisi.view.CustomLoadMoreView;

import java.util.ArrayList;
import java.util.List;


public class EquipListFragment extends BaseFragment {

    private LinearLayout[] linearLayouts;

    //切换账户
    private TextView tv_transfer;
    private RecyclerView listView;
    private SwipeRefreshLayout refreshLayout;
    private Handler handler;
    private RecyclerView deptListView;

    private TextView tv_all;
    private TextView tv_online;
    private TextView tv_offline;
    private TextView tv_inactive;

    private LinearLayout ll_all;
    private LinearLayout ll_online;
    private LinearLayout ll_offline;
    private LinearLayout ll_inactive;

    int selectedIndex; // 选中的fragment
    int currentIndex = 0; // 当前显示的fragment

    int selectIndex;// 每次点击记录的值
    int tempIndex; // 点击确定选中的值

    private PopupWindow popupWindow;
    private View popupView;

    private EquipListAdapter listAdapter;
    private DeptListAdapter deptListAdapter;

    private List<EquipBean.Result.Items> equipsList = new ArrayList();// 设备列表

    private List<DeptsEntity.Result> resultList = new ArrayList();
    private List<DeptsEntity.Result> deptsList = new ArrayList();

    private static int page = 1;//页数
    private int size = 10;//记录数
    private String status = Constant.DEVICE_ALL;//记录数
    private EquipBean eEntity;
    String deptId;

    private boolean isShow;

    @Override
    public View initView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_equip_list,null);
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        deptId = (String) SpUtil.get(Constant1.UNDERLING_DEPTID,"");
        loadDeptsData();
        refresh();
    }

    @Override
    protected void getExtras(View view) { }

    @Override
    protected void findView(View view) {
        tv_transfer = view.findViewById(R.id.tv_transfer);
        String name = (String) SpUtil.get(Constant1.DEPT_NAME,"");
        tv_transfer.setText(name);

        /**********/
        listView = view.findViewById(R.id.rv_eq_list);
        listView.setLayoutManager(new LinearLayoutManager(mContext));

        listAdapter = new EquipListAdapter(R.layout.eq_list_item_view, equipsList);
        listAdapter.bindToRecyclerView(listView);
        listAdapter.disableLoadMoreIfNotFullPage();
        listAdapter.setLoadMoreView(new CustomLoadMoreView());

        listView.setLayoutManager(new LinearLayoutManager(mContext));
        listView.setAdapter(listAdapter);
        /**********/

        tv_all = view.findViewById(R.id.tv_all);
        tv_online = view.findViewById(R.id.tv_online);
        tv_offline = view.findViewById(R.id.tv_offline);
        tv_inactive = view.findViewById(R.id.tv_inactive);

        ll_all = view.findViewById(R.id.ll_all);
        ll_online = view.findViewById(R.id.ll_online);
        ll_offline = view.findViewById(R.id.ll_offline);
        ll_inactive = view.findViewById(R.id.ll_inactive);

        linearLayouts = new LinearLayout[]{ll_all,ll_online,ll_offline,ll_inactive};
        linearLayouts[0].setSelected(true);// 一开始显示第一个

        MyLinearListener myLinearListener = new MyLinearListener();
        for (int i = 0; i < linearLayouts.length; i++) {
            linearLayouts[i].setOnClickListener(myLinearListener);
        }


        /** 下级部门(popup view)相关*/
        popupView = LayoutInflater.from(mActivity).inflate(R.layout.layout_popup_window,null);

        deptListView = popupView.findViewById(R.id.popup_recycler_view);
        deptListView.setLayoutManager(new LinearLayoutManager(mContext));

        deptListAdapter = new DeptListAdapter(deptsList);
        deptListView.setAdapter(deptListAdapter);
        deptListAdapter.setOnItemClickListener(index -> {
            selectIndex = index;
            Log.e("222eeeee","点击的index = "+index);
            deptListAdapter.setSelectIndex(index);
            // 刷新适配器
            deptListAdapter.notifyDataSetChanged();
        });

        popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT,true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(R.style.anim_menu_bottombar);
        popupWindow.setOnDismissListener(() -> setBackgroundAlpha(1.0f));

        /** 下拉刷新*/
        refreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue);

        //refresh();
    }

    class MyLinearListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ll_all:
                    selectedIndex = 0;
                    status = Constant.DEVICE_ALL;
                    break;
                case R.id.ll_online:
                    selectedIndex = 1;
                    status = Constant.DEVICE_ON_LINE;
                    break;
                case R.id.ll_offline:
                    selectedIndex = 2;
                    status = Constant.DEVICE_OFF_LINE;
                    break;
                case R.id.ll_inactive:
                    selectedIndex = 3;
                    status = Constant.DEVICE_NO_USE;
                    break;
            }
            // 如果点击的不是当前的第一个Fragment
            if (selectedIndex != currentIndex) {
                linearLayouts[currentIndex].setSelected(false);
                linearLayouts[selectedIndex].setSelected(true);
                currentIndex = selectedIndex;
            }

            isShow = true;
            page = 1;
            refresh();
        }
    }

    @Override
    protected void setListener(View view) {

        listAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                EquipBean.Result.Items item = equipsList.get(position);
                switch (view.getId()) {
                    case R.id.liner_history:
                        if (ButtonUtil.isFastClick()) {//历史轨迹
                            // IntentUtil.gotoActivity(mContext,HistoryTraceActivity.class,false,map);
                            Intent intent = new Intent();
                            intent.putExtra("eqNo", item.getEqNo());//存入当前设备
                            intent.putExtra("ownerName",item.getOwnerName() == null ? "":item.getOwnerName());//存入当前车主姓名
                            intent.setClass(mContext, HistoryTraceActivity.class);
                            mContext.startActivity(intent);
                        }
                        break;
                    case R.id.liner_navi: //一键导航
                        if (ButtonUtil.isFastClick()) {
                            if(item.getPoint() != null && item.getPoint() != null){
                                Intent intent =new Intent(mContext, AccountChaseCarAcitivty.class);
                                TrackEntity data = new TrackEntity();
                                TrackEntity.Result dataResult = new TrackEntity.Result();
                                dataResult.setGdLat(item.getPoint().getLat());
                                dataResult.setGdLng(item.getPoint().getLng());
                                ArrayList<TrackEntity.Result> results = new ArrayList<>();
                                results.add(dataResult);
                                data.setResults(results);
                                intent.putExtra(Constant.ACCOUNT_NAVIGATION, data);
                                mContext.startActivity(intent);
                            } else {
                                ToastUtil.show("无设备位置信息");
                            }
                        }
                        break;

                    case R.id.liner_track:
                        if(item.getPoint() != null && item.getPoint().getLat() != null){
                            Intent intent = new Intent();
                            intent.putExtra("eqNo", item.getEqNo());//存入当前设备
                            intent.putExtra("ownerName",item.getOwnerName());
                            intent.setClass(mContext, TracingActivity.class);
                            mContext.startActivity(intent);
                        }else {
                            ToastUtil.show("无设备位置信息");
                        }
                        break;
                    case R.id.liner_notice:
                        if(ButtonUtil.isFastClick()){
                            Intent intent=new Intent();
                            intent.putExtra("eqNo", item.getEqNo());//存入当前设备编码
                            intent.putExtra("deptId",item.getDeptId());//存入当前部门编码
                            intent.putExtra("eqName",item.getOwnerName());//存入姓名
                            intent.setClass(mContext, AlarmListActivity.class);
                            mContext.startActivity(intent);
                        }
                        break;
                    case R.id.liner_user_content:
                        if(ButtonUtil.isFastClick()){
                            Intent intent = new Intent();
                            Log.e("点击点击","eqNo = "+item.getEqNo());
                            Log.e("点击点击","deptId = "+item.getDeptId());
                            intent.putExtra("eqNo", item.getEqNo());//设备号
                            intent.putExtra("deptId",item.getDeptId());//型号
                            intent.setClass(mContext, AccountUserInfoActivity.class);
                            mContext.startActivity(intent);
                        }
                        break;
                }
            }
        });

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isShow = false;
                listAdapter.setEnableLoadMore(false);
                page = 1;
                refresh();
            }
        });

        listAdapter.setOnLoadMoreListener(() -> {
            isShow = false;
            Log.e("999000","触发上拉加载功能");
            refresh();
        },listView);

        /** 切换账户*/
        tv_transfer.setOnClickListener(v -> {
            setBackgroundAlpha(0.5f);
            popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
            deptListAdapter.setSelectIndex(tempIndex);
            deptListAdapter.notifyDataSetChanged();
        });
        // 取消
        popupView.findViewById(R.id.btn_cancel).setOnClickListener(v -> popupWindow.dismiss());
        // 确定
        popupView.findViewById(R.id.btn_confirm).setOnClickListener(v -> {
            Log.e("eee999存储deptId：","click");
            tempIndex = selectIndex;
            popupWindow.dismiss();
            /** 切换账户时，同步存储该账户部门deptId，并刷新数据*/
            DeptsEntity.Result r = deptsList.get(tempIndex);
            Log.e("eee999存储deptId：",""+r.getDeptId());
            SpUtil.put(Constant1.UNDERLING_DEPTID,r.getDeptId());
            Log.e("eee999存储deptId：","click"+SpUtil.get(Constant1.UNDERLING_DEPTID,""));
            tv_transfer.setText(r.getDeptName());
            isShow = true;
            page = 1;
            refresh();
        });
    }

    private void setBackgroundAlpha(float alpha) {
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = alpha;
        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        mActivity.getWindow().setAttributes(lp);
    }

    private void showEmpty() {
        listAdapter.setEmptyView(R.layout.layout_empty);
    }


    /** 加载设备列表*/
    public void refresh(){// deptId使用最新的deptId,即从下属账户选择的deptId;登录时此值已同步存储。
        //deptId = mSharePreference.getInt(Constant.ACCOUNT_CHILD_DEPTID,Constant.SP_NULL)+"";
        deptId = (String) SpUtil.get(Constant1.UNDERLING_DEPTID,"");
        Api.getInstance().createService().loadEquipList(deptId,page,size,status,"")
                .compose(RxSchedulers.observableIO2Main(mContext))
                .subscribe(new ProgressObserver<EquipBean>(mContext,isShow){
                    @Override
                    public void onSuccess(EquipBean result) {
                        List data = result.getResult().get(0).getItems();
                        refreshLayout.setRefreshing(false);
                        eEntity = result;
                        if (page == 1) {
                            if (data.size() == 0) showEmpty();
                            updateEquipsCount();
                            equipsList.clear();
                            equipsList.addAll(data);
                            listAdapter.setNewData(equipsList);
                        } else {
                            listAdapter.addData(data);
                        }

                        if (data.size() < size) {
                            listAdapter.loadMoreEnd();
                        } else {
                            listAdapter.loadMoreComplete();
                        }
                        page++;
                    }

                    @Override
                    public void onFailure(ErrorException e) {
                        refreshLayout.setRefreshing(false);
                        listAdapter.loadMoreFail();
                        showEmpty();
                        Log.e("999000", "code = " + e.getCode());
                    }
                });
    }

    @SuppressLint("SetTextI18n")
    public void updateEquipsCount(){
        String total = eEntity.getResult().get(1).getTotal();
        if (total == null) total = "0";
        String ol = eEntity.getResult().get(1).getOl();
        if (ol == null) ol = "0";
        String off = eEntity.getResult().get(1).getOff();
        if (off == null) off = "0";
        String unact = eEntity.getResult().get(1).getUnact();
        if (unact == null) unact = "0";

        tv_all.setText("全部(" + total + ")");
        tv_online.setText("在线(" + ol + ")");
        tv_offline.setText("离线(" + off + ")");
        tv_inactive.setText("未启用(" + unact + ")");
    }

    /** 加载下属帐号列表*/
    public void loadDeptsData(){
        int deptId = Integer.parseInt((String)SpUtil.get(Constant1.DEPTID,""));
        final String parentDeptId = (String)SpUtil.get(Constant1.SUPER_DEPTID,"");
        Api.getInstance().createService()
                .loadDeptList(deptId+"")
                .compose(RxSchedulers.observableIO2Main(mContext))
                .subscribe(new ProgressObserver<DeptsEntity>(mContext,false) {
                    @Override
                    public void onSuccess(DeptsEntity result) {
                        new Thread(() -> {
                            resultList = result.getResult();
                            treeList(Integer.parseInt(parentDeptId),0,resultList);
                            Message message = new Message();
                            message.obj = deptsList;
                            handler.sendMessage(message);
                        }).start();

                        handler = new Handler(){
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                deptsList = (List<DeptsEntity.Result>)msg.obj;
                                deptListAdapter.notifyDataSetChanged();
                            }
                        };
                    }

                    @Override
                    public void onFailure(ErrorException e) {

                    }
                });
    }

    public void treeList(int parentId, int level, List<DeptsEntity.Result> list) {
        int i = 0;
        for (DeptsEntity.Result r : list) {
            int id = Integer.parseInt(r.getDeptId());
            int pid = Integer.parseInt(r.getParentDeptId());
            int k = 0;
            if (parentId == pid) {k++;}

            if (k != 0) {
                DeptsEntity.Result rt = list.get(i);
                rt.setLevel(level+1);
                deptsList.add(rt);
                treeList(id,level+1,list);
            }
            i++;
        }
    }
}
